package com.example.studyllm.utils;

import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class HttpClientUtils {

    private static final int CONNECT_TIMEOUT = 5000; // 连接超时时间（毫秒）
    private static final int SOCKET_TIMEOUT = 5000;  // 读取超时时间（毫秒）

    private HttpClientUtils() {
        // 私有构造方法，防止实例化
    }

    @SneakyThrows
    public static ResponseResult sendGet(HttpQueryParams httpQueryParams) {
        String url = httpQueryParams.getUrl();
        Map<String, String> headers = httpQueryParams.getHeaders();
        Map<String, String> params = httpQueryParams.getParams();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = params.entrySet().stream()
                        .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
                        .collect(Collectors.toList());
                uriBuilder.addParameters(pairs);
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            if (headers != null && !headers.isEmpty()) {
                headers.forEach((key, value) -> httpGet.addHeader(new BasicHeader(key, value)));
            }
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return handleResponse(response);
        } catch (Exception e) {
            throw new HttpClientException("GET 请求失败", e);
        } finally {
            httpClient.close();
        }
    }

    @SneakyThrows
    public static ResponseResult sendPost(HttpQueryParams httpQueryParams) {
        String url = httpQueryParams.getUrl();
        Map<String, String> headers = httpQueryParams.getHeaders();
        Map<String, String> params = httpQueryParams.getParams();
        Object body = httpQueryParams.getBody();
        ContentType contentType = httpQueryParams.getContentType();
        if (contentType == null) {
            contentType = ContentType.APPLICATION_JSON;
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置请求头
            if (headers != null && !headers.isEmpty()) {
                headers.forEach((key, value) -> httpPost.addHeader(new BasicHeader(key, value)));
            }
            // 设置请求参数
            if (params != null && !params.isEmpty()) {
                HttpEntity entity = new StringEntity(new URIBuilder().addParameters(
                        params.entrySet().stream()
                                .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
                                .collect(Collectors.toList())
                ).toString(), ContentType.APPLICATION_FORM_URLENCODED);
                httpPost.setEntity(entity);
            }
            // 设置请求体
            if (body != null) {
                HttpEntity entity = new StringEntity(body.toString(), contentType);
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return handleResponse(response);
        } catch (Exception e) {
            throw new HttpClientException("POST 请求失败", e);
        } finally {
            httpClient.close();
        }
    }

    private static ResponseResult handleResponse(CloseableHttpResponse response) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();
     /*   Map<String, String> responseHeaders = response.getAllHeaders().stream()
                .collect(Collectors.toMap(
                        header -> header.getName(),
                        header -> header.getValue(),
                        (v1, v2) -> v2
                ));*/
        String responseBody = EntityUtils.toString(response.getEntity());
        return new ResponseResult(statusCode, null, responseBody);
    }

    public static class ResponseResult {
        private final int statusCode;
        private final Map<String, String> headers;
        private final String body;

        public ResponseResult(int statusCode, Map<String, String> headers, String body) {
            this.statusCode = statusCode;
            this.headers = headers;
            this.body = body;
        }

        public int getStatusCode() {
            return statusCode;
        }

        public Map<String, String> getHeaders() {
            return headers;
        }

        public String getBody() {
            return body;
        }
    }

    public static class HttpClientException extends RuntimeException {
        public HttpClientException(String message, Throwable cause) {
            super(message, cause);
        }
    }
/*
    public static void main(String[] args) {
        try {
            // 示例：GET 请求
            Map<String, String> getHeaders = Map.of("Content-Type", "application/json");
            Map<String, String> getParams = Map.of("name", "test", "age", "20");
            ResponseResult getResponse = HttpClientUtils.sendGet("http://example.com/api", getHeaders, getParams);
            System.out.println("GET Response Status: " + getResponse.getStatusCode());
            System.out.println("GET Response Body: " + getResponse.getBody());

            // 示例：POST 请求
            Map<String, String> postHeaders = Map.of("Content-Type", "application/json");
            Map<String, String> postParams = Map.of("name", "test", "age", "20");
            String postBody = "{\"username\": \"test\", \"password\": \"123456\"}";
            ResponseResult postResponse = HttpClientUtils.sendPost("http://example.com/api", postHeaders, postParams, postBody, ContentType.APPLICATION_JSON);
            System.out.println("POST Response Status: " + postResponse.getStatusCode());
            System.out.println("POST Response Body: " + postResponse.getBody());
        } catch (HttpClientException e) {
            e.printStackTrace();
        }
    }*/
}